import { Component, OnInit, Output, Input, EventEmitter, ElementRef } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import { Observable } from 'rxjs';
import { Subject } from 'rxjs/Subject';
import { Search } from './shared/search.model';
import { SearchService } from './shared/search.service';

@Component({
	selector: 'mySearch',
	templateUrl: 'search.component.html',
	providers: [SearchService],
	styleUrls: ['search.component.scss']
})

export class SearchComponent implements OnInit {
	//向父组件传递list
	@Output("searchList")
	searchList1: EventEmitter<Search[]> = new EventEmitter<Search[]>();
	@Output('loading')
	loading: EventEmitter<boolean> = new EventEmitter<boolean>();

	search: Search[] = [];
	//父组件传入查询类型条件
	@Input("searchType")
	searchType: string;
	searchString: string;
	public searchKey: Subject<string> = new Subject<string>();
	constructor(private searchService: SearchService, private el: ElementRef) { }

	ngOnInit() {
		this.searchKey
			// .filter((text: string) => text.length > 1)
			.distinctUntilChanged()
			.debounceTime(400)
			// .do(() => this.loading.next(true))
			// .map(data => this.searchService.getList(this.searchType, this.searchString))
			// .switch()//返回最近一次请求
			.subscribe((searchString) => {
				this.loading.next(true);
				console.log(this.searchString);
				this.searchService.getList(this.searchType, this.searchString)
					// .do(() => this.loading.next(true))
					.subscribe(
					(res) => {
						this.searchList1.emit(res);
						 this.loading.next(false);
					},
					(err) => {
						this.searchList1.emit(err);
						 this.loading.next(false)
					},
				);
				// this.search = res;
				// this.searchList1.emit(res);
				// this.loading.next(false);
			},
			(err) => {
				this.searchList1.emit(err);
				this.loading.next(false)
			},
			 () => this.loading.next(false)
		)
		// Observable.fromEvent(this.el.nativeElement,"keyup")
		// .map((e: any) => e.target.value)
		// .filter((text: string) => text.length > 1) 
		// .debounceTime(400)
		// .do(()=>this.loading.next(true))
		// .distinctUntilChanged()//检查是否请求改变
		// .map(data=>this.searchService.getList(this.searchType,this.searchKey))
		// .switch()//返回最近一次请求
		// .subscribe((res) => {
		// 	this.search = res;
		// 	this.searchList1.emit(res);
		// 	this.loading.next(false);
		// },
		// (err)=>{
		// 	this.searchList1.emit(err);
		// 	this.loading.next(false)
		// },
		// ()=>this.loading.next(false))
		// //初始化的时候不调用后台搜索
		// // this.searchList();

	}
	keyUpseach($event):void {
		this.searchKey.next(this.searchString);
	}
}